package com.rivues.module.manage.web.handler.report;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.model.ConfigureParam;
import com.rivues.module.platform.web.model.DataDic;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.RivuTools;
import com.rivues.util.service.cache.CacheHelper;

@Controller
@RequestMapping("/{orgi}/manage/reports/{service}")
public class ReportController extends Handler {

	/**
	 * 
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/index", name = "index", type = "manage", subtype = "reports")
	public ModelAndView index(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String service,
			@Valid String ex,@Valid String code) throws Exception {
		ModelAndView view = request(
				super.createManageTempletResponse("/pages/manage/report/reportsetting"),
				orgi);
		if (ex != null) {
			view.addObject("ex", ex);
		}
		if(code != null){
			view.addObject("code",code);
		}
		User user = super.getUser(request);
		if(user != null){
			view = readreport(view, orgi, user, service);
			if(!service.equals("report")){
				//获取到公共的配置信息
				List<ConfigureParam> configs = super.getService().findAllByCriteria(DetachedCriteria.forClass(ConfigureParam.class).add(Restrictions.eq("protype", "reports")).add(Restrictions.eq("orgi", orgi)));
				//查询到当前报表或者报表目录设置信息
				List<ConfigureParam> params = super.getService().findAllByCriteria(DetachedCriteria.forClass(ConfigureParam.class).add(Restrictions.eq("protype", service)).add(Restrictions.eq("orgi", orgi)));
				for (ConfigureParam param : params) {
					for (ConfigureParam config : configs) {
						String name = config.getName()+"."+param.getProtype();
						if(param.getName().equals(name)){
							config.setValue(param.getValue());
						}
					}
				}
				view.addObject("propertiesList",configs);
			}
		}
		view.addObject("type", service);
		view.addObject("stype", "reports");
		return view;
	}

	/**
	 * 
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/reportsetting", name = "reportsetting", type = "manage", subtype = "reports")
	public ModelAndView reportsetting(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String service,
			@Valid String ex) throws Exception {
		ModelAndView view = request(
				super.createManageTempletResponse("/pages/manage/report/reportsetting"),
				orgi);
		if (ex != null) {
			view.addObject("ex", ex);
		}
		User user = super.getUser(request);
		if (user != null) {
			view = readreport(view, orgi, user, service);
			if(!service.equals("report")){
				//获取到公共的配置信息
				List<ConfigureParam> configs = super.getService().findAllByCriteria(DetachedCriteria.forClass(ConfigureParam.class).add(Restrictions.eq("protype", "reportdata")).add(Restrictions.eq("orgi", orgi)));
				//查询到当前报表或者报表目录设置信息
				List<ConfigureParam> params = super.getService().findAllByCriteria(DetachedCriteria.forClass(ConfigureParam.class).add(Restrictions.eq("protype", service)).add(Restrictions.eq("orgi", orgi)));
				for (ConfigureParam param : params) {
					for (ConfigureParam config : configs) {
						String name = config.getName()+"."+param.getProtype();
						if(param.getName().equals(name)){
							config.setValue(param.getValue());
						}
					}
				}
				view.addObject("propertiesList",configs);
			}
		}
		view.addObject("type", service);
		view.addObject("stype", "reportdata");
		view.addObject("code","true");
		return view;
	}

	/**
	 * 
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/propertiessettingeditdof", name = "propertiessettingeditdof", type = "manage", subtype = "reports")
	public ModelAndView propertiessettingeditdof(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String service,
			@Valid ConfigureParam param) throws Exception {
		int count = super.getService().getCountByCriteria(
				DetachedCriteria.forClass(ConfigureParam.class)
						.add(Restrictions.eq("id", param.getId()))
						.add(Restrictions.eq("orgi", orgi)));
		if (count == 1) {
			ConfigureParam temp = (ConfigureParam) super.getService()
					.getIObjectByPK(ConfigureParam.class, param.getId());
			
			temp.setValue(param.getValue());
			param = temp;
			String name = param.getName()+"."+service;
			List<ConfigureParam> configs = super.getService().findAllByCriteria(
					DetachedCriteria.forClass(ConfigureParam.class)
					.add(Restrictions.eq("name", name))
					.add(Restrictions.eq("orgi", orgi)));
			param.setName(name);
			param.setOrgi(orgi);
			param.setProtype(service);
			param.setId(RivuTools.md5(name));
			if(configs == null || configs.size() == 0){
				super.getService().saveIObject(param);
			}else{
				super.getService().updateIObject(param);
			}
			
			CacheHelper.getDistributedDictionaryCacheBean().update(
					param.getName(), orgi, param.getValue());
		}
		ModelAndView view = request(
				super.createPageResponse("/pages/public/success"), orgi);
		view.addObject("type", service);
		view.addObject(
				"propertiesList",
				super.getService().findAllByCriteria(
						DetachedCriteria.forClass(ConfigureParam.class)
								.add(Restrictions.eq("protype", service))
								.add(Restrictions.eq("orgi", orgi))));
		return view;
	}
	
	
	/**
	 * 
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/propertiessettingeditdo", name = "propertiessettingeditdo", type = "manage", subtype = "reports")
	public ModelAndView propertiessettingeditdo(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String service,
			@Valid ConfigureParam param,@Valid String stype) throws Exception {
		ResponseData response = new ResponseData(
				"redirect:/{orgi}/manage/system/{service}/index.html?code=cur");
		//根据类型查询对应的报表目录或者报表数据
		if(stype.equals("reportdata")){
			DataDic dic = (DataDic) super.getService().getIObjectByPK(DataDic.class, service);
			if(dic != null){
				//查询同级是否存在该目录名称，如果存在则不修改该目录名称，并提示用户修改的目录名称已存在
				List<DataDic> dics = super.getService().findAllByCriteria(DetachedCriteria.forClass(DataDic.class)
						.add(Restrictions.eq("name", param.getValue()))
						.add(Restrictions.eq("orgi", orgi))
						.add(Restrictions.eq("parentid", dic.getParentid())));
				if(dics == null || dics.size() ==0){
					dic.setName(param.getValue());
					super.getService().updateIObject(dic);
					response = new ResponseData(
							"redirect:/{orgi}/manage/reports/{service}/index.html?code=cur");
				}else{
					response = new ResponseData(
							"redirect:/{orgi}/manage/reports/{service}/index.html?code=cur&msgcode=E_REPORT_10010004");
				}
			}
		}else{
			//查询同级是否存在该目录名称，如果存在则不修改该目录名称，并提示用户修改的目录名称已存在
			PublishedReport report = (PublishedReport) super.getService().getIObjectByPK(PublishedReport.class, service);
			if(report != null){
				List<PublishedReport> reports = super.getService().findAllByCriteria(DetachedCriteria.forClass(PublishedReport.class)
						.add(Restrictions.eq("name", param.getValue()))
						.add(Restrictions.eq("orgi", orgi))
						.add(Restrictions.eq("dicid", report.getDicid())));
				if(reports == null || reports.size() == 0){
					report.setName(param.getValue());
					super.getService().updateIObject(report);
					response = new ResponseData(
							"redirect:/{orgi}/manage/reports/{service}/index.html");
				}else{
					response = new ResponseData(
							"redirect:/{orgi}/manage/reports/{service}/index.html?msgcode=E_REPORT_10010006");
				}
			}
		}
		return super.request(response, orgi);
	}

	/**
	 * 查询当前报表目录和报表信息
	 * @param view
	 * @param orgi
	 * @param user
	 * @param id
	 * @return
	 */
	private ModelAndView readreport(ModelAndView view, String orgi, User user,String id) {
		//查询获取到报表目录信息
		List<DataDic> diclist = super.getService()
				.findAllByCriteria(DetachedCriteria.forClass(DataDic.class)
						.add(Restrictions.or(
								Restrictions.eq("creater",user.getId()),
								Restrictions.and(Restrictions.eq("status",RivuDataContext.ReportStatusEnum.AVAILABLE.toString()),
								Restrictions.eq("publishedtype",RivuDataContext.ReportStatusEnum.PUBLISHED.toString()))))
						.add(Restrictions.eq("orgi", orgi))
						.add(Restrictions.eq("tabtype",RivuDataContext.TabType.PUB.toString()))) ;
		view.addObject("dicList",diclist);
		if(id != null && id != ""){
			for (DataDic dataDic : diclist) {
				if(dataDic.getId().equals(id)){
					view.addObject("data",dataDic);
					break;
				}
			}
		}
		
		//查询获取到报表数据
		List<PublishedReport> reportList = super.getService()
				.findAllByCriteria(DetachedCriteria.forClass(PublishedReport.class)
						.add(Restrictions.or(
								Restrictions.eq("creater",user.getId()),
								Restrictions.and(Restrictions.eq("status",RivuDataContext.ReportStatusEnum.AVAILABLE.toString()),
								Restrictions.eq("publishedtype",RivuDataContext.ReportStatusEnum.PUBLISHED.toString()))))
						.add(Restrictions.eq("orgi", orgi))
						.add(Restrictions.eq("reporttype", "report"))
						.add(Restrictions.eq("tabtype",RivuDataContext.TabType.PUB.toString())));
		view.addObject("reportList", reportList);
		
		if(id != null && id != ""){
			for (PublishedReport publishedReport : reportList) {
				if(publishedReport.getId().equals(id)){
					view.addObject("data",publishedReport);
					break;
				}
			}
		}
		
		return view;
	}

}
